package com.example.NetworkSender.network;

import android.util.Log;

public class NetworkManager {

    private final int port;
    private NetworkListener netListener;
    private NetworkSender netSender;

    Thread thrListener;
    Thread thrSender;

    public NetworkManager(int port) {
        this.port = port;
        netListener = new NetworkListener(port);
        thrListener = new Thread(netListener);
        thrListener.start();
    }

    public int getData(int[] buf) {
        Log.e("NetworkManager.getData", "started rcv");
        synchronized (netListener.lockObj) {
            if (netListener.hasNewData) {
                Log.e("NetworkManager.getData", "has data");
                System.arraycopy(netListener.buffer, 0, buf, 0, netListener.size);
                netListener.hasNewData = false;
                return netListener.size;
            }
        }
        Log.e("NetworkManager.getData", "has no data");
        return 0;
    }

    public void sendData(String address, int[] buf, int size) {
        try {
            if (thrSender != null && thrSender.isAlive()) {
                netSender.stop();
            }
        } catch (Exception ex) {
            Log.e("NetworkManager.sendData", ex.getMessage());
        }
        try {
            netSender = new NetworkSender(address, port);
            thrSender = new Thread(netSender);
            thrSender.start();
        } catch (Exception ex) {
            Log.e("NetworkManager.sendData2", ex.getMessage());
        }
        synchronized (netSender.lockObj) {
            if (!netSender.hasDataToSend) {
                System.arraycopy(buf, 0, netSender.buffer, 0, size);
                netSender.size = size;
                netSender.hasDataToSend = true;
            }
        }
    }
}
